package util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class CommonUtil {
	
	/** Retrieves a link to which the transitive address follows. For that, the HTTPRequest is performed which 
	 *  may result in network delays. If the function fails to accomplish the request, the input URL is returned **/
	public static String getDestinationOfTransitiveURL(String transitiveURL) {
		String referedToURL = transitiveURL;
		URL url;
		try {
			url = new URL(transitiveURL);
			URLConnection con = url.openConnection();
			con.addRequestProperty("User-Agent", "Mozilla/5.0");
			BufferedReader in = new BufferedReader(
		                                new InputStreamReader(
		                                		con.getInputStream()));
			referedToURL = con.getURL().toString();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return referedToURL;
	}
	
	public static String getFileExtension(String fileURL) {
		String ext = "";
		int lastDotPos = fileURL.lastIndexOf('.');
		if (lastDotPos>=0) {
			ext = fileURL.substring(lastDotPos+1);
		}
		return ext;
	}
	
	public static String getFileNameWithExtension(String fileURL) {
		String fileName = null;
		int lastSlashPos = fileURL.lastIndexOf('/');
		if (lastSlashPos>=0) {
			fileName = fileURL.substring(lastSlashPos+1);
		}
		return fileName;
	}
	
	public static String getFileNameWithoutExtension(String fileURL) {
		String fileName = null;
		int lastSlashPos = fileURL.lastIndexOf('/');
		int lastDotPos = fileURL.lastIndexOf('.');
		if (lastSlashPos>=0) {
			if (lastDotPos>lastSlashPos) {
				fileName = fileURL.substring(lastSlashPos+1, lastDotPos);
			} else {
				fileName = fileURL.substring(lastSlashPos+1);
			}
		}
		return fileName;
	}
	
	public static String getDomainFromLink(String URL) {
		URL = URL.replace("http://", "");
		int firstSlashPos = URL.indexOf('/');
		if (firstSlashPos>0) {
			URL = URL.substring(0, firstSlashPos);
		}
		return URL;
	}
}
